<script setup>
	import * as echarts from 'echarts'
	import {onMounted} from "vue";
	import {ref} from "vue";
	import {chartApi} from "@/api/chart.js";
	import {deptApi} from "@/api/dept.js";
	
	const chartRef = ref()
	let dept=[]
	
	onMounted(()=> {
		deptApi.selectAll().then(result=>{
			console.log(result.data)
			for(let item of result.data){
				dept.push(item.name)
			}
			console.log(dept)
		})
		const myChart = echarts.init(chartRef.value)
		chartApi.selectReimCount().then(result => {
			if (result.code == 0) {
				let list = result.data
				let newResult = []
				newResult.push(['amount', 'deptName', 'month'])
				list.forEach(item => {
					newResult.push([item.amount, item.deptName, item.month]);
				})
				console.log(newResult)
				run(newResult)
			}
			
			function run(_rawData) {
				const datasetWithFilters = [];
				const seriesList = [];
				echarts.util.each(dept, function (dept) {
					var datasetId = 'dataset_' + dept;
					datasetWithFilters.push({
						id: datasetId,
						fromDatasetId: 'dataset_raw',
						transform: {
							type: 'filter',
							config: {
								and: [
									{dimension: 'deptName', '=': dept}
								]
							}
						}
					});
					seriesList.push({
						type: 'line',
						datasetId: datasetId,
						showSymbol: false,
						name: dept,
						endLabel: {
							show: true,
							formatter: function (params) {
								return params.value[1] + ': ' + params.value[0];
							}
						},
						labelLayout: {
							moveOverlap: 'shiftY'
						},
						emphasis: {
							focus: 'series'
						},
						encode: {
							x: 'month',
							y: 'amount',
							label: ['deptName', 'amount'],
							itemName: 'month',
							tooltip: ['amount']
						}
					});
				});
				var option;
				option = {
					animationDuration: 10000,
					dataset: [
						{
							id: 'dataset_raw',
							source: _rawData
						},
						...datasetWithFilters
					],
					title: {
						text: '各部门当年每月报销统计图'
					},
					tooltip: {
						order: 'valueDesc',
						trigger: 'axis'
					},
					legend: {
						data: dept,
						left: 'right'
						
					},
					xAxis: {
						type: 'category',
						nameLocation: 'middle',
						name: '月份'
					},
					yAxis: {
						name: '报销金额'
					},
					grid: {
						right: 140
					},
					series: seriesList
				};
				myChart.setOption(option);
			}
		})
		window.onresize = function () {
			myChart.resize();
		};
	})


</script>

<template>
	<div ref="chartRef" style="width: 100%;height: 100%"></div>
</template>

<style scoped>

</style>